<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/6/13
 * Time: 23:31
 */

namespace app\common\model;

use think\Cache;
use think\Model;

/**
 * 文章评论点赞相关模型
 * Class ArticleCommentGood
 * @package app\common\model
 */
class ArticleCommentGood extends Base
{
    protected $table = 'wechatadmin.system_comment_good';

    const ARTICLE_COMMENT_GOOD = 'article_comment_good_'; //文章评论点赞缓存键名
    const CACHE_TIME = 86400;

    /**
     * 关联文章评论
     * @return \think\model\relation\belongsTo
     */
    public function comments()
    {
        return $this->belongsTo('ArticleComment', 'id', 'comment_id');
    }

    /**
     * 获取评论的所有点赞用户id字符串
     * 方便计算点赞数量 与 用户是否点赞的判断
     * TODO 需要把ucid 替换成使用 uid
     * TODO 该评论点赞状态未完成
     * @param array $map
     * @return array|bool|int|mixed
     */
    public function getCommentGood($map = [])
    {
        $aid = $map['aid'];
        $ucid = $map['ucid'];
        $ac_id = $map['ac_id'];
        $uid = $map['uid'];

        $comment_good = false;
        if ($this->cache_on >= 1) {
            // 从缓存获取当前用户
            $comment_good = Cache::get(self::ARTICLE_COMMENT_GOOD . $ac_id . '_' . $uid);
        }

        if ($comment_good === false) {
            try {
                $comment_good = $this->where(['aid' => $aid, 'ucid' => $ucid, 'comment_id' => $ac_id])
                    ->findOrFail()->toArray();
                $comment_good = json_decode(json_encode($comment_good, true), true);

                if (!empty($comment_good)) $comment_good = 1;
            } catch (\Exception $e) {
                $comment_good = 0;
            }

            Cache::set(self::ARTICLE_COMMENT_GOOD . $ac_id, $comment_good, self::CACHE_TIME); // 根据评论id
        }

        return $comment_good;
    }


    /**
     * 获取去当前用户所有点赞的评论id
     * @param array $map
     * @return array|bool|mixed|\PDOStatement|string|Model
     */
    public function getAllCommentGood($map = [])
    {
        $ucid = $map['ucid'];
        $uid = $map['uid'];

        $comment_good = false;
        if ($this->cache_on >= 1) {
            // 从缓存获取当前用户
            $comment_good = Cache::get(self::ARTICLE_COMMENT_GOOD . $uid);
        }

        if ($comment_good === false) {
            try {
                $comment_good = $this
                    ->field('ucid,aid,comment_id')
                    ->where(['ucid' => $ucid])
                    ->selectOrFail();
                $comment_good = json_decode(json_encode($comment_good, true), true);

            } catch (\Exception $e) {
                $comment_good = [];
            }

            if ($this->cache_on >= 1)
                Cache::set(self::ARTICLE_COMMENT_GOOD . $uid, $comment_good, self::CACHE_TIME); // 根据评论id
        }

        return $comment_good;
    }

}
